package com.yanqu.road.dao.impl.player;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.npc.UserNpcTalk;

import java.sql.*;

public class UserNpcTalkDaoImpl extends TempDataObjectDao<UserNpcTalk> {

	public UserNpcTalk getUserNpcTalk(long userId) {
		ResultSet rs = null;
		CallableStatement call = null;
		String sql = "select * from t_u_npc_talk where userId=?";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareCall(sql);
			call.setLong(1, userId);
			rs = call.executeQuery();
			while (rs.next()) {
				UserNpcTalk data = parse(rs);
				return data;
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			getDb().closeConnection(call, rs);
		}
		return null;
	}

	@Override
	protected boolean addData(UserNpcTalk data) {
		PreparedStatement call = null;
		String sql = "INSERT INTO t_u_npc_talk(userId,`no`,eventId,reward,refreshTime,isGetReward,status) VALUES(?,?,?,?,?,?,?)";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareStatement(sql);
			int i = 1;
			call.setLong(i++, data.getUserId());
			call.setInt(i++, data.getNo());
			call.setInt(i++, data.getEventId());
			call.setString(i++, data.getReward());
			call.setLong(i++, data.getRefreshTime());
			call.setBoolean(i++, data.isGetReward());
			call.setInt(i++, data.getStatus());
			return call.executeUpdate() > 0;
		} catch (Exception e) {
			logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
		} finally {
			getDb().closeConnection(call, null);
		}
		return false;
	}

	@Override
	protected boolean updateData(UserNpcTalk data) {
		PreparedStatement call = null;
		String sql = "UPDATE t_u_npc_talk SET `no`=?,eventId=?,reward=?,refreshTime=?,isGetReward=?,status=? WHERE userId = ?";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareStatement(sql);
			int i = 1;
			call.setInt(i++, data.getNo());
			call.setInt(i++, data.getEventId());
			call.setString(i++, data.getReward());
			call.setLong(i++, data.getRefreshTime());
			call.setBoolean(i++, data.isGetReward());
			call.setInt(i++, data.getStatus());
			call.setLong(i++, data.getUserId());
			return call.executeUpdate() > 0;
		} catch (Exception e) {
			logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
		} finally {
			getDb().closeConnection(call, null);
		}
		return false;
	}

	@Override
	protected UserNpcTalk parseData(ResultSet rs) throws SQLException {
		UserNpcTalk data = new UserNpcTalk();
		data.setUserId(rs.getLong("userId"));
		data.setNo(rs.getInt("no"));
		data.setEventId(rs.getInt("eventId"));
		data.setReward(rs.getString("reward"));
		data.setStatus(rs.getInt("status"));
		data.setRefreshTime(rs.getLong("refreshTime"));
		data.setGetReward(rs.getBoolean("isGetReward"));
		return data;
	}

}
